package lesson3.models;

import components.CircleCollider;
import components.HP;
import components.SpriteBar;
import java2d.game.Maths;
import java2d.game.SpriteGameObject;
import java2d.game.Time;

import java.awt.geom.Point2D;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/4/18 18:34
 */
public abstract class Spacecraft extends SpriteGameObject implements HP.ValueChanged {

    public final Point2D shootDirection = new Point2D.Double();

    public final SpriteBar hpBar = new SpriteBar();

    public final CircleCollider collider = new CircleCollider();

    public final HP hp = new HP();

    public double shootInterval = 1d;

    public boolean canShoot = true;

    public String targetTag;

    private double shootTimer;

    public Spacecraft(String spritePath) {
        super(spritePath);

        hp.setMaxValue(100);
        hp.reset();
        hp.valueChanged = this;
        addComponent(hp);

        add(hpBar);

        collider.visible = false;
        addComponent(collider);
    }

    public Bullet shoot(Point2D direction) {
        if (isDestroyed() || !canShoot)
            return null;

        Bullet bullet = new Bullet(this, targetTag);
        bullet.transform.setPosition(transform.getPosition());
        bullet.transform.setLocalRotation(Maths.toRotation(direction));
        bullet.translator.direction.setLocation(direction);
        getScene().add(bullet);
        bullet.translator.begin();

        return bullet;
    }

    public void changed(int newValue, int oldValue) {
        if (isDestroyed())
            return;

        hpBar.setRatio(hp.getRatio());

        if (newValue <= 0) {
            die();
        }
    }

    public void die() {
        Explosion explosion = new Explosion();
        explosion.transform.setPosition(transform.getPosition());
        explosion.transform.setLocalScale(2, 2);
        getScene().add(explosion);

        destroy();
    }

    @Override
    protected void onUpdate() {
        updateIntervalShoot();
    }

    protected void updateIntervalShoot() {
        if (shootTimer >= shootInterval) {
            Bullet bullet = shoot(shootDirection);

            if (bullet != null)
                setupBullet(bullet);

            shootTimer = 0;
        } else {
            shootTimer += Time.deltaTime;
        }
    }

    protected void setupBullet(Bullet bullet) {
    }
}
